<template>
  <div class="edit-component">
    <el-form :inline="false" :model="formData" :rules="validatorRules" ref="formData" label-width="80px">
      <el-form-item label="培训标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入培训标题"></el-input>
      </el-form-item>
      <el-form-item label="主讲人" prop="speaker">
        <el-input v-model="formData.speaker"  placeholder="主讲人(可点击右侧加号选择)" suffix-icon="" >
			<i slot="suffix" class="icon el-icon-circle-plus-outline" @click="openUserCheck('speaker')"></i>
		</el-input>
      </el-form-item>
	  <el-form-item label="培训时间" prop="time">
		  <el-date-picker
				  v-model="formData.time"
				  type="datetimerange"
				  range-separator="至"
				  :value-format="timeFormat"
				  start-placeholder="开始时间"
				  end-placeholder="结束时间">
		  </el-date-picker>
	  </el-form-item>
	  <el-form-item label="培训地点" prop="place">
	    <el-input v-model="formData.place" placeholder="请输入培训地点" ></el-input>
	  </el-form-item>
	  <el-form-item label="培训对象" prop="trainers">
	    <el-input v-model="formData.trainers"  placeholder="培训对象(可点击右侧加号选择)"  suffix-icon="" >
			<i slot="suffix" class="icon el-icon-circle-plus-outline" @click="openUserCheck('trainers')"></i>
		</el-input>
	  </el-form-item>
	  <el-form-item label="培训内容" prop="trainContent" class="textarea">
	    <el-input type="textarea" v-model="formData.trainContent" maxlength="200" autosize  placeholder="最多可输入200字" show-word-limit></el-input>
	  </el-form-item>
		<el-form-item label="考核方式" prop="evalMode">
			<!-- 下拉选择 -->
			<el-select v-model="formData.evalMode" filterable placeholder="请选择">
				<el-option
					v-for="item in checkMethods"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select>
		</el-form-item>
		<!-- 文件上传 -->
		<el-form-item label="培训资料" prop="trainFiles">
			<el-upload
					class="upload-demo"
					ref="upload"
					action="#"
					:on-change="fileChange"
					:on-remove="fileRemove"
					:file-list="formData.trainFiles"
					:multiple="true"
					:auto-upload="false">
				<el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
			</el-upload>
		</el-form-item>
    </el-form>
    <div class="button-bar">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
    </div>
	<userSelector class="uselector"  ref="userSelector" :initData="checkValue" @output="checkedUser"></userSelector>
  </div>
</template>
<script>
import userSelector from "@/components/userSelector"
export default {
	components:{userSelector},
    props:{
      rowId:{
        type:String,
        default:"",
        required:true,
      },
    },
    data(){
      return{
        formData:{
            id:'',
            title:'',
		    time:"",
			speakerId:"",
			speaker:"",
			startTime:"",
			endTime:"",
			place:"",
			trainers:"",
			trainersId:"",
			trainFiles:[],
			trainContent:""
		},
		  checkValue:"",
		  curFiles:"",
        validatorRules:{
          title:[
            {required: true, message: '请输入培训名称', trigger: 'blur'},
			  { min: 2, max: 20, message: "长度在 2 到 20 个字符"}
          ],
			time:[
		    {required: true, message: '请选择时间', trigger: 'blur'},
		  ],
			speaker:[
		       {required: true, message: '请选择主讲人', trigger: 'blur'},
			],
			place:[
		        {required: true, message: '请输入培训地点'},
				{ min: 2, max: 50, message: "长度在 2 到 50 个字符"}
		  ],
			trainers:[
				{required: true, message: '请选择培训对象'}
			],
			trainContent:[
				{required: true, message: '请输入培训内容'}
			]
        },
		showPoint:"",
		pointIndex:1,
		timeFormat:"yyyy-MM-dd HH:mm:ss",
		checkMethods:[],
		editModle:null,
		btnLoading:false,
      }
    },
    watch:{
      rowId(){
        this.initFormData()
      }
    },
    methods:{
		initFormData(){
			if(!this.rowId){
				this.resetForm();
				return
			}
			this.$http.getTrainById({id:this.rowId})
			.then((res)=>{
				this.editModle = res.data.data ||{};
				this.resetForm();
			}).catch((err)=>{
				throw(err)
			})
		},
		//审核资料上传文件上传
		fileChange(file,fileList){
          this.formData.trainFiles = fileList ||[];
		},
		fileRemove(file,fileList){
			this.formData.trainFiles = fileList ||[];
		},
       //打开人员选择弹出框
		openUserCheck(filed){
			this.checkValue = this.formData[filed];
			this.curFiles = filed;
			this.$refs.userSelector.showDialog=true
		},
      submit(){
        var isValidate=false
        this.$refs.formData.validate((bool)=>{
            isValidate=bool
        })
        if(!isValidate){return}

		  let submitData = new FormData();
		  this.formData.startTime = this.formData.time[0];
		  this.formData.endTime = this.formData.time[1];
          for(var key in this.formData){
          	if(key == "trainFiles" && this.formData.trainFiles.length > 0){
          		var fileUrls = [];
          		for(var i = 0;i < this.formData.trainFiles.length;i++){
          			if(this.formData.trainFiles[i].status && this.formData.trainFiles[i].status == "ready" ){
						submitData.append("file"+i,this.formData.trainFiles[i].raw);
					}else if(this.formData.trainFiles[i].status && this.formData.trainFiles[i].status == "complete"){
						fileUrls.push(this.formData.trainFiles[i].url)
					}
				}
				if(fileUrls.toString()!=""){
					submitData.append("trainFiles",fileUrls.toString());
				}
			}else{
          		submitData.append(key,this.formData[key]);
			}
		  }
		  this.btnLoading=true;
		  if(this.formData.id){
			  this.$http.updTrain(submitData)
			  .then((res)=>{
				  this.$message.success("操作成功！")
				  this.resetForm()
				  this.$emit("refresh")
				  this.$emit('closeDialog',false)
				  this.btnLoading=false
			  }).catch((err)=>{
				  this.btnLoading=false
				  throw(err)
			  })
		  }else{
			  this.$http.addTrain(submitData)
			  .then((res)=>{
				  this.$message.success("操作成功！")
				  this.resetForm()
				  this.$emit("refresh")
				  this.$emit('closeDialog',false)
				  this.btnLoading=false
			  }).catch((err)=>{
				  this.btnLoading=false
				  throw(err)
			  })
		  }

      },

      resetForm(){
			if(this.rowId && this.editModle){//编辑模式
				for(var key in this.editModle){
					if(key == "trainFiles"){
						if(this.editModle.trainFiles){
							var files = this.editModle.trainFiles.split(",");
							for (var i = 0;i < files.length;i++){
								var lastX = files[i].lastIndexOf("/")+1;
								var obj = {
									name:files[i].substring(lastX),
									status:"complete",
									url:files[i]
								}
								this.formData.trainFiles.push(obj);
							}
						}else{
							this.formData[key] = [];
						}
					}else {
						this.$set(this.formData,key,this.editModle[key] || "")
					}
				}
				this.formData.time = [];
				this.formData.time[0] = this.editModle.startTime;
				this.formData.time[1] = this.editModle.endTime;
			}else {//新建模式
				for(var key in this.formData){
					if(key == "trainFiles"){
						this.formData[key] = [];
					}else {
						this.formData[key]=""
					}
				}
			}
      },

      cancel(){
        this.resetForm()
        //this.$emit("refresh")
        this.$emit('closeDialog',false)
      },

	  checkedUser(users){
		  var ids=users.map((item)=>{
			  return item.id
		  }).toString()
		  var names=users.map((item)=>{
			  return item.name
		  }).toString()
		  this.$set(this.formData,this.curFiles+"Id",ids)
		  this.$set(this.formData,this.curFiles,names)
	  },
		getCheckMethods(){
			this.$http.getDictKeyList({parentCode:'evalMode'})
					.then((res)=>{
						this.checkMethods = res.data.data ||[]
					}).catch((err)=>{
				throw(err)
			})
		}
    },
	created() {
		this.initFormData()
		this.getCheckMethods();
	}


  }
</script>
<style scoped lang='scss'>
#clickMap{
	flex:1;
}

</style>


